<template >
    <rx-dialog @handOk="handleSubmit" @cancel="cancel" :showok="showok" btnalign="Right">
        <div slot="toolbar">
            <a-button v-if="!showok" type="primary" @click="nextStep">
                {{i18n('list.nextStep','下一步')}}
            </a-button>
            <a-button v-else type="primary" @click="backStep">
                {{i18n('list.previous','上一步')}}
            </a-button>

        </div>
        <rx-layout class="custom-layout">
            <div slot="center">
                <!--   第一步基本信息     -->
                <a-form-model ref="form" :model="mdl" style="height: 100%;" :rules="rules">
                    <div class="div-containers" :class="{'div-containers-show':showok}" @click="sqlShow = ''">

                        <a-row>
                            <a-col :span="12">
                                <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" :label="i18n('form.name','名称')" prop="name">
                                    <a-input :placeholder="i18n('form.name','名称')"
                                             v-model="mdl.name"
                                             @blur.native="getPinyinByName(mdl.name)"
                                             style="width: 100%;"/>

                                </a-form-model-item>
                            </a-col>
                            <a-col :span="12">
                                <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" :label="i18n('form.identificationName','标识名')" prop="key">
                                    <a-input :placeholder="i18n('form.identificationName','标识名')"
                                             v-model="mdl.key"
                                             style="width: 100%;"/>
                                </a-form-model-item>
                            </a-col>
                            <a-col :span="12">
                                <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" :label="i18n('form.classify','分类')"  prop="treeId">
                                    <rx-category-select cat-key="FORM" :isGrant="true"
                                                        v-model="mdl.treeId" v-if="isShowManageTree" :isAdmin="isManageToTree"
                                                        style="width: 100%;"></rx-category-select>
                                </a-form-model-item>
                            </a-col>
                            <a-col :span="12">
                                <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" :label="i18n('form.dataSourceName','数据源名称')" >
                                    <a-input-group compact>
                                        <a-input :placeholder="i18n('form.dataSourceName','数据源名称')" allow-clear
                                                 v-model="mdl.dsAlias"
                                                 style="width:calc(100% - 45px)"/>
                                        <a-button @click="openDataSource">
                                            <my-icon type="iconsearch"></my-icon>
                                        </a-button>
                                    </a-input-group>
                                </a-form-model-item>
                            </a-col>
                        </a-row>

                        <a-row>
                            <a-col :span="24">
                                <a-form-model-item :labelCol="labelCol1" :wrapperCol="wrapperCol1" :label="i18n('form.sqlBuildType','SQL构建类型')">
                                    <div class="sqlBuildTypeList">
                                        <div class="sqlBuildTypeList-child" @click="sqlTypeChange(obj.value)" :class="{'sqlBuildTypeList-show': mdl.sqlBuildType==obj.value}" v-for="(obj,index) in sqlBuildTypeList">
                                            <div v-if="mdl.sqlBuildType===obj.value" class="sqlBuildTypeList-child-iconfont">

                                            </div>
                                            <div>{{obj.name}}</div>
                                            <span>{{obj.text}}</span>
                                        </div>
                                    </div>
                                </a-form-model-item>
                            </a-col>
                        </a-row>

                        <a-row v-show="isTable">
                            <a-col :span="24">
                                <a-form-model-item :labelCol="labelCol1" :wrapperCol="wrapperCol1" :label="i18n('form.tableOrViewName','表名或视图名')" >
                                    <a-input-group compact>
                                        <a-input :placeholder="i18n('form.objectName','对象名称(表名或视图名)')"
                                                 allow-clear
                                                 v-model="mdl.tableName"
                                                 style="width:calc(100% - 45px)"/>
                                        <a-button @click="openTableQuery">
                                            <my-icon type="iconsearch"></my-icon>
                                        </a-button>
                                    </a-input-group>
                                </a-form-model-item>
                            </a-col>
                        </a-row>

                        <a-row v-if="!isTable">
                            <a-col :span="24">
                                <a-form-model-item :label-col="labelCol1" :wrapper-col="wrapperCol1" label="SQL" :required="true">
                                    <div
                                        style="box-sizing: border-box;margin-right: 1px;height:400px;">
                                        <rx-monaco-editor
                                            ref="sql"
                                            v-model="mdl.sql"
                                            language="sql"
                                        >
                                    <span slot="monacoeditor" id="sqlShow">
                                        <div v-show="!isGroovy" class="conditionDiv">
                                            <div class="minDiv" style="margin-left: 20px">
                                                <div class="form-condition" @click.stop="sqlShow ='sqlCondition'"><my-icon type="iconxinzeng" style="margin-right: 5px"></my-icon>
                                                    <span>
                                                        {{i18n('form.insertField','插入条件字段')}}
                                                    </span>
                                                </div>
                                                <div class="opinion-parenthesis" v-show="sqlShow=='sqlCondition'">
                                                    <div class="opinion-parenthesis-triangle"></div>
                                                        <div style="position: relative">
                                                            <ul class="opinion-parenthesis-list">
                                                                <li v-for="(time,index) in sqlWhereField" v-if="time.label" :key="index">
                                                                    <my-icon @click.stop="sqlRemoveFields(index)" type="iconoffline" ></my-icon>
                                                                    <div @click.stop="sqlInsertChange(time.value)">{{time.label}}</div>
                                                                </li>
                                                            </ul>
                                                            <div class="opinion-parenthesis-add" @click.stop="sqIinterposition('where')"><my-icon type="iconxinzeng"></my-icon>
                                                                {{i18n('form.addField','添加条件字段')}}
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="minDiv">
                                                    <div class="form-condition" @click.stop="sqlShow = 'sqlConstant'"><my-icon type="iconxinzeng" style="margin-right: 5px"></my-icon>
                                                        <span>
                                                            {{i18n('form.insertConstant','插入常量')}}
                                                        </span></div>
                                                        <div class="opinion-parenthesis" id="sqlConstant" v-show="sqlShow=='sqlConstant'">
                                                            <div class="opinion-parenthesis-triangle"></div>
                                                            <div style="position: relative">
                                                                <ul class="opinion-parenthesis-list">
                                                                    <li v-for="(time,index) in constantField" v-if="time.label" :key="index">
                                                                        <div @click.stop="sqlInsertChange(time.value)">{{time.label}}</div>
                                                                    </li>
                                                                </ul>
                                                            </div>
                                                        </div>
                                                </div>
                                                <div class="minDiv">
                                                    <div class="form-condition" @click.stop="sqlShow = 'sqlContext'"><my-icon type="iconxinzeng" style="margin-right: 5px"></my-icon>
                                                        <span>{{i18n('form.insertSQL','插入上下文的SQL条件参数')}}</span></div>
                                                    <div class="opinion-parenthesis" id="sqlContext" v-show="sqlShow=='sqlContext'">
                                                        <div class="opinion-parenthesis-triangle"></div>
                                                        <div style="position: relative">
                                                            <ul class="opinion-parenthesis-list">
                                                                <li v-for="(time,index) in sqlContext" :key="index">
                                                                    <div @click.stop="onSqlExp(time)">{{time.name}}</div>
                                                                </li>
                                                            </ul>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="minDiv">
                                                    <div class="form-condition" @click="insertTreeSql"><my-icon type="iconxinzeng" style="margin-right: 5px"></my-icon>
                                                        <span>{{i18n('form.insertTreeSQL','插入树状Sql')}}</span></div>
                                                </div>
                                        </div>
                                    </span>
                                        </rx-monaco-editor>
                                    </div>
                                </a-form-model-item>
                            </a-col>
                        </a-row>

                        <a-row>
                            <a-col :span="12">
                                <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" :label="i18n('form.isPage','是否分页')">
                                    <a-radio-group :placeholder="i18n('form.isPage','是否分页')" v-model="mdl.isPage">
                                        <a-radio value="1">
                                            {{i18n('isPageMap.yes','是')}}
                                        </a-radio>
                                        <a-radio value="0">
                                            {{i18n('isPageMap.no','否')}}
                                        </a-radio>
                                    </a-radio-group>
                                </a-form-model-item>
                            </a-col>
                            <a-col v-show="mdl.isPage==1" :span="12">
                                <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" :label="i18n('form.pageSize','分页大小')" >
                                    <a-input-number :min="1" :max="1000" :placeholder="i18n('form.pageSize','分页大小')"
                                                    v-model="mdl.pageSize"
                                    />
                                </a-form-model-item>
                            </a-col>

                        </a-row>
                    </div>
                    <!--第二步-->
                    <div class="condition-field" v-if="showok">
                        <div style="padding: 10px">
                            <!--返回字段-->
                            <div class="div-containers">
                                <div class="div-containers-head">
                                    <div>
                                <span class="div-containers-head-span">
                                    {{i18n('form.returnField','返回字段')}}
                                </span>
                                    </div>
                                    <div class="tableToolBar">
                                        <a-button type="primary" @click="selectColumn('query')">
                                            {{i18n('isButton.columnHeader','列头设置')}}
                                        </a-button>
                                        <a-button type="danger" @click="removeFields('query')">
                                            {{$ti18('rxList.delBtn','删除')}}
                                        </a-button>
                                        <a-button type="primary" @click="moveUp('query')">
                                            {{i18n('isButton.upward','向上')}}
                                        </a-button>
                                        <a-button type="primary" @click="moveDown('query')">
                                            {{i18n('isButton.down','向下')}}
                                        </a-button>
                                    </div>
                                </div>
                                <a-table :dataSource="returnFields"
                                         :pagination="false"
                                         bordered
                                         rowKey="idx_"
                                         :rowSelection="{selectedRowKeys: selectedReturnRowKeys,type:'checkbox', onChange: onSelectReturnChange}"
                                         :customRow="customReturnRowFn"
                                         :columns="returnColumns"
                                         :key=keys>
                                <span slot="reg" slot-scope="text,record,index">
                                  <rx-input-button @click="regDialog" @change="regChange($event,record)"
                                                   v-model="record.regName"></rx-input-button>
                                </span>
                                </a-table>
                            </div>
                            <!-- 条件字段-->
                            <div v-if="mdl.sqlBuildType =='table'" class="div-containers">
                                <div class="div-containers-head">
                                    <div>
                                <span class="div-containers-head-span">
                                    {{i18n('form.conditionField','条件字段')}}
                                </span>
                                    </div>
                                    <div class="tableToolBar">
                                        <a-button type="primary" @click="selectColumn('where')">
                                            {{i18n('isButton.columnHeader','列头设置')}}
                                        </a-button>
                                        <a-button type="danger" @click="removeFields('where')">
                                            {{$ti18('rxList.delBtn','删除')}}
                                        </a-button>
                                        <a-button type="primary" @click="moveUp('where')">
                                            {{i18n('isButton.upward','向上')}}
                                        </a-button>
                                        <a-button type="primary" @click="moveDown('where')">
                                            {{i18n('isButton.down','向下')}}
                                        </a-button>
                                    </div>
                                </div>
                                <a-table :dataSource="whereFields"
                                         :pagination="false"
                                         rowKey="idx_"
                                         bordered
                                         :rowSelection="{selectedRowKeys: selectedWhereRowKeys,type:'checkbox', onChange: onSelectWhereChange}"
                                         :customRow="customWhereRowFn"
                                         :columns="whereColumns">
                                <span slot="typeOperate" slot-scope="text, record, index">
                                    <a-select v-if="record.columnType=='varchar' || record.columnType=='clob'" :defaultValue="text"
                                              @change="typeOperateChange">
                                      <a-select-option value="=" :key="index">{{i18n('isTypeOperate.equal','等于')}}</a-select-option>
                                      <a-select-option value="!=" :key="index">{{i18n('isTypeOperate.notEqual','不等于')}}</a-select-option>
                                      <a-select-option value="LI" :key="index">{{i18n('isTypeOperate.fuzzyQuery','模糊查询')}}</a-select-option>
                                      <a-select-option value="LL" :key="index">{{i18n('isTypeOperate.leftQuery','左模糊查询')}}</a-select-option>
                                      <a-select-option value="LR" :key="index">{{i18n('isTypeOperate.rightQuery','右模糊查询')}}</a-select-option>
                                      <a-select-option value="IN" :key="index">IN</a-select-option>
                                    </a-select>
                                  <a-select v-if="record.columnType=='number' || record.columnType=='int' || record.columnType=='date'" :defaultValue="text"
                                            @change="typeOperateChange">
                                      <a-select-option value="=" :key="index">{{i18n('isTypeOperate.equal','等于')}}</a-select-option>
                                      <a-select-option value="!=" :key="index">{{i18n('isTypeOperate.notEqual','不等于')}}</a-select-option>
                                      <a-select-option value="<" :key="index">{{i18n('isTypeOperate.lessThan','小于')}}</a-select-option>
                                      <a-select-option value="<=" :key="index">{{i18n('isTypeOperate.lessOrEqual','小于等于')}}</a-select-option>
                                      <a-select-option value=">" :key="index">{{i18n('isTypeOperate.greater','大于')}}</a-select-option>
                                      <a-select-option value=">=" :key="index">{{i18n('isTypeOperate.greatOrEqual','大于等于')}}</a-select-option>
                                      <a-select-option value="BETWEEN" :key="index">BETWEEN</a-select-option>
                                    </a-select>
                                   </span>
                                    <span slot="valueSource" slot-scope="text, record, index">
                                    <a-select :defaultValue="text" @change="valueSourceChange" style="width: 100%">
                                      <a-select-option value="param" :key="index">{{i18n('isTypeOperate.paraPass','参数传入')}}</a-select-option>
                                      <a-select-option value="fixedVar" :key="index">{{i18n('isTypeOperate.fixValue','固定值')}}</a-select-option>
                                      <a-select-option value="script" :key="index">{{i18n('isTypeOperate.script','脚本')}}</a-select-option>
                                      <a-select-option value="constantVar" :key="index">{{i18n('isTypeOperate.constant','常量')}}</a-select-option>
                                    </a-select>
                                   </span>
                                    <span slot="valueDef" slot-scope="text, record, index">
                                    <a-input v-if="record.valueSource=='fixedVar'" :defaultValue="text" @change="valueDefTextChange($event,record,index)"/>
                                    <a-input-group v-if="record.valueSource=='script'" compact>
                                      <a-input v-model="record.valueDef" />
                                      <a-button @click="openScriptQuery(record)">...</a-button>
                                    </a-input-group>
                                    <a-select v-if="record.valueSource=='constantVar'" :defaultValue="text" :options="constantField"
                                              @change="valueDefChange($event,index)" style="width: 100%"></a-select>
                                   </span>
                                </a-table>
                            </div>
                            <!-- 排序字段-->
                            <div class="div-containers">
                                <div class="div-containers-head">
                                    <div>
                                <span class="div-containers-head-span">
                                     {{i18n('form.sortField','排序字段')}}
                                </span>
                                    </div>
                                    <div class="tableToolBar">
                                        <a-button type="primary" @click="selectColumn('order')">
                                            {{i18n('isButton.columnHeader','列头设置')}}
                                        </a-button>
                                        <a-button type="danger" @click="removeFields('order')">
                                            {{$ti18('rxList.delBtn','删除')}}
                                        </a-button>
                                        <a-button type="primary" @click="moveUp('order')">
                                            {{i18n('isButton.upward','向上')}}
                                        </a-button>
                                        <a-button type="primary" @click="moveDown('order')">
                                            {{i18n('isButton.down','向下')}}
                                        </a-button>
                                    </div>
                                </div>
                                <a-table :dataSource="orderFields"
                                         :pagination="false"
                                         rowKey="idx_"
                                         bordered
                                         :rowSelection="{selectedRowKeys: selectedOrderRowKeys,type:'checkbox', onChange: onSelectOrderChange}"
                                         :customRow="customOrderRowFn"
                                         :columns="orderColumns">
                               <span slot="typeOrder" slot-scope="text, record, index">
                                <a-select :defaultValue="text" @change="typeOrderChange">
                                  <a-select-option value="ASC" :key="index">
                                      {{i18n('isTypeOrder.ASC','升序')}}
                                  </a-select-option>
                                  <a-select-option value="DESC" :key="index">
                                      {{i18n('isTypeOrder.DESC','降序')}}
                                  </a-select-option>
                                </a-select>
                               </span>
                                </a-table>
                            </div>
                        </div>
                        <div v-show="isGroovy">
                            <!--自定义sql-->
                            <div class="conditionDiv-sql">
                                <div>
                                    <span class="div-containers-head-span">
                                        {{i18n('form.customSQL','自定义SQL')}}
                                    </span>
                                </div>
                                <div style="box-sizing: border-box;height:400px;margin-top: 20px">
                                    <rx-monaco-editor
                                        ref="sqlDiy"
                                        v-model="mdl.sqlDiy"
                                        language="java">
                                <span slot="monacoeditor">
                                    <div  class="conditionDiv">
                                        <div class="minDiv" style="margin-left: 20px">
                                            <div class="form-condition" @click.stop="sqlShow ='sqlCondition'"><my-icon style="margin-right: 5px" type="iconxinzeng"></my-icon>
                                                <span>
                                                    {{i18n('form.insertField','插入条件字段')}}
                                                </span></div>
                                            <div class="opinion-parenthesis" v-show="sqlShow=='sqlCondition'">
                                                <div class="opinion-parenthesis-triangle"></div>
                                                <div style="position: relative">
                                                    <ul class="opinion-parenthesis-list">
                                                        <li v-for="(time,index) in sqlWhereField" v-if="time.label" :key="index">
                                                            <my-icon @click.stop="sqlRemoveFields(index)" type="iconoffline" ></my-icon>
                                                            <div @click.stop="sqlDiyInsertChange(time.value)">{{time.label}}</div>
                                                        </li>
                                                    </ul>
                                                    <div class="opinion-parenthesis-add" @click.stop="sqIinterposition('where')"><my-icon type="iconxinzeng"></my-icon>
                                                        {{i18n('form.addField','添加条件字段')}}
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="minDiv" >
                                            <div class="form-condition" @click.stop="sqlShow = 'sqlConstant'"><my-icon type="iconxinzeng" style="margin-right: 5px"></my-icon>
                                                <span>
                                                    {{i18n('form.insertConstant','插入常量')}}
                                                </span></div>
                                            <div class="opinion-parenthesis" v-show="sqlShow=='sqlConstant'">
                                                <div class="opinion-parenthesis-triangle"></div>
                                                <div style="position: relative">
                                                    <ul class="opinion-parenthesis-list">
                                                        <li v-for="(time,index) in constantField" v-if="time.label" :key="index">
                                                            <div @click.stop="sqlDiyInsertChange(time.value)">{{time.label}}</div>
                                                        </li>
                                                    </ul>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="minDiv" >
                                            <div class="form-condition" @click.stop="insertTreeSql"><my-icon type="iconxinzeng" style="margin-right: 5px"></my-icon>
                                                <span>
                                                    {{i18n('form.insertTreeSQL','插入树状Sql')}}
                                                </span></div>
                                        </div>
                                    </div>
                                </span>
                                    </rx-monaco-editor>
                                </div>
                            </div>
                        </div>
                    </div>
                </a-form-model>
            </div>
        </rx-layout>
    </rx-dialog>
</template>
<script>
    import FormCustomQueryApi from '@/api/form/core/formCustomQuery'
    import {BaseFormModel, RxDialog, GridMixin, Dialog, RxMonacoEditor, RxLayout, RxInputButton,JsConstant,Util} from "@lowcode/jpaas-common-lib"
    import DialogBox from "@/assets/js/DialogBox";
    import reloadColumnDialog from "@/views/modules/form/core/listLayout/reloadColumnDialog";



    export default {
        name: 'FormCustomQueryEdit',
        mixins: [BaseFormModel, GridMixin],
        components: {
            RxDialog,
            RxMonacoEditor,
            RxLayout,
            RxInputButton
        },
        data() {
            return {
                showok:false,
                activeKey: "baseInfo",
                isTable: true,
                isGroovy: false,
                sqlWhereField: [],
                constantField: [],
                returnFields: [],
                returnColumns: [
                    {title: this.i18n('form.fieldComment','字段注解'), dataIndex: 'comment'},
                    {title: this.i18n('form.fieldName','字段名'), dataIndex: 'fieldName'},
                    {title: this.i18n('form.replacementRules','替换规则'), dataIndex: 'reg', scopedSlots: {customRender: 'reg'}}],
                selectedReturnRowKeys: [],
                whereFields: [],
                whereColumns: [

                    {title: this.i18n('form.fieldComment','字段注解'), dataIndex: 'comment'},
                    {title: this.i18n('form.fieldName','字段名'), dataIndex: 'fieldName'},
                    {title: this.i18n('form.dataType','数据类型'), dataIndex: 'columnType'},
                    {
                        title: this.i18n('form.operationType','操作类型'),
                        dataIndex: 'typeOperate',
                        scopedSlots: {customRender: 'typeOperate'},
                        width: "80"
                    },
                    {title: this.i18n('form.valueSource','值来源'), dataIndex: 'valueSource', scopedSlots: {customRender: 'valueSource'}, width: "100"},
                    {title: this.i18n('form.default','默认值'), dataIndex: 'valueDef', scopedSlots: {customRender: 'valueDef'}, width: "100"}],
                selectedWhereRowKeys: [],

                orderFields: [],
                orderColumns: [
                    {title: this.i18n('form.fieldComment','字段注解'), dataIndex: 'comment'},
                    {title: this.i18n('form.fieldName','字段名'), dataIndex: 'fieldName'},
                    {title: this.i18n('form.sortType','排序类型'), dataIndex: 'typeOrder', scopedSlots: {customRender: 'typeOrder'}}],
                selectedOrderRowKeys: [],
                keys: 'k',
                isTenant:false,
                sqlBuildTypeList:[
                    {
                        name:this.i18n('form.tablesOrViews','基于表或视图'),
                        text:this.i18n('form.text1','直接通过选择表或视图的方式构建SQL'),
                        value:'table'
                    },
                    {
                        name:'GroovySQL',
                        text:this.i18n('form.text2','通过JAVA代码的方式返回SQL语句 ，这种方式是最灵活的'),
                        value:'sql'
                    },{
                        name:'FreemarkSql',
                        text:this.i18n('form.text3','这种方式是通过 Freemark的语法构建SQL'),
                        value:'freeMarkerSql'
                    }
                ],
                columnData:[],
                sqlShow:"",
                sqlContext:[
                    {
                        key:'{CREATE_BY_}',
                        name:this.i18n('form.currentUserID','当前用户ID'),
                    },{
                        key:'{DEP_ID_}',
                        name:this.i18n('form.currentDepartmentID','当前部门ID'),
                    },{
                        key:'{TENANT_ID_}',
                        name:this.i18n('form.currentOrganizationID','当前机构ID'),
                    },{
                        key:'{COMPANY_ID_}',
                        name:this.i18n('form.currentCompanyID','当前公司ID'),
                    }
                ],
                rules:{
                    name: [{ required: true, message: this.i18n('form.nameR','名称必填'), trigger: 'change' }],
                    key: [
                        { required: true, message: this.i18n('form.aliasR','别名必填'), trigger: 'change' },
                        {pattern:/^[a-zA-Z][a-zA-Z0-9_-]*$/,message:this.i18n('form.str','不能以数字开头,不能包含【_-】以外的特殊字符！','input')}
                    ],
                    treeId: [{ required: true, message: this.i18n('form.classificationR','分类必填'), trigger: 'change' }]

                },


            }
        },
        created() {
            this.isUserManager(this.$route.query.appId);
            //常量
            this.loadConstants();
        },
        mounted() {
        },
        methods: {
            i18n(name,text,key){
                return this.$ti18(name,text,"formCustomQuery",key);
            },
            getPinyinByName(name){
                var self_=this
                //如果标识键存在，跳过
                if (!name || this.mdl.key){
                    return;
                }
                this.getPinyin(name).then(res => {
                    //去除不可见的特殊符号
                    if(res){
                        res=res.replace(/\u200B/g,'');
                    }
                    self_.mdl.key=res
                });
            },
            sqIinterposition(id){

                this.showDialog(function (self, data) {
                    self.addData(id, data);
                    if (id == "where") {
                        self.sqlWhereField = self.sqlWhereField.concat(data.map(where => {
                            var show = true
                            self.sqlWhereField.map(time=>{
                                if(time.value ==where.fieldName){
                                    show=false
                                }
                            })
                            if(show){
                                return {label: where.fieldLabel, value: where.fieldName}
                            }else {
                                return false
                            }
                        }));
                    }
                })
            },
            //获取返回字段
            loadDataSource(){

                var queryType = this.mdl.sqlBuildType;
                var dsId = this.mdl.dsAlias;
                var query = "";
                if (queryType == "table") {
                    var tableName = this.mdl.tableName;
                    if (tableName == "") {
                        this.$message.warning(this.i18n('form.msg1','请先选择对象!'));
                        return;
                    }
                    query = tableName;
                } else {
                    // Groovy或freemarket情况
                    this.setSqlDiy();
                    var sql = this.isGroovy?(this.mdl.sqlDiy?this.mdl.sqlDiy:this.mdl.sql):this.mdl.sql;
                    if (!sql) {
                        this.$message.warning(this.i18n('form.msg2','请填写SQL!'));
                        return;
                    }
                    query = sql;
                    queryType=this.isGroovy?"sql":"freeMarkerSql";
                }
                var parameter = {
                    query:query,
                    queryType:queryType,
                    ds:dsId || ""
                }
                FormCustomQueryApi.findColumnList(parameter).then(res =>{
                    if(res.success==false){
                        this.$message.warning(this.i18n('form.msg3','请填写正确的sql'));
                    }else {
                        this.showok = true;
                    }
                })
            },
            regChange(data, record) {
                if (data != "") {
                    record.reg = JSON.parse(data).value;
                } else {
                    record.reg = "";
                }
                record.regName = data;
            },
            regDialog(vm) {
                DialogBox.openRegLib({
                    curVm: this, widthHeight: ['900px', '600px'], data: {multiSelect: false}
                }, function (data) {
                    vm.setVal(data.regId, data.name);
                })
            },
            onload_(data) {
                if (!data) {
                    let obj={name:"",key:"",tableName:"",dsAlias:"",
                        whereField:"",resultField:"",
                        orderField:"",table:1,sqlDiy:"",sql:"",
                        treeId:"",isTenant:"",sqlBuildType: 'table',
                        isPage: '0', pageSize: 20
                    }
                    this.$set(this,"mdl",obj) ;
                    this.sqlTypeChange('table',"init");
                } else {
                    data.isPage = data.isPage.toString();
                    this.sqlTypeChange(data.sqlBuildType,"init");
                    this.returnFields = data.resultField ? JSON.parse(data.resultField) : [];
                    this.whereFields = data.whereField ? JSON.parse(data.whereField) : [];
                    this.orderFields = data.orderField ? JSON.parse(data.orderField) : [];
                    this.sqlWhereField = this.sqlWhereField.concat(this.whereFields.map(where => {
                        return {label: where.comment, value: where.fieldName}
                    }));
                    this.isTenant=data.isTenant=="1"?true:false;
                }
            },
            loadConstants() {
                FormCustomQueryApi.getConstants().then(data => {
                    this.constantField = this.constantField.concat(data.map(item => {
                        return {label: item.val, value: item.key}
                    }));
                })
            },
            selectColumn(id) {
                this.showDialog(function (self, data) {
                    self.addData(id, data);
                    if (id == "where") {
                        self.sqlWhereField = self.sqlWhereField.concat(data.map(where => {
                            return {label: where.fieldLabel, value: where.fieldName}
                        }));
                    }
                })
            },
            showDialog(callback) {
                var queryType = this.mdl.sqlBuildType;
                var dsId = this.mdl.dsAlias;
                var query = "";
                if (queryType == "table") {
                    var tableName = this.mdl.tableName;
                    if (tableName == "") {
                        this.$message.warning(this.i18n('form.msg1','请先选择对象!'));
                        return;
                    }
                    query = tableName;
                } else {
                    var sql = queryType=="sql"?this.mdl.sqlDiy:this.mdl.sql;
                    if (!sql) {
                        alert(this.i18n('form.msg2','请填写SQL!'));
                        return;
                    }
                    query = sql;
                }
                let params={query: query, queryType: queryType, ds: dsId};
                FormCustomQueryApi.findColumnList(params).then(list => {
                    let conf = {
                        component: reloadColumnDialog,
                        title:  '列头设置',
                        curVm: this,
                        data: {
                            reloadFields: list,
                            header:'fieldLabel',
                            field:'fieldName'
                        },
                        widthHeight: ['800px', '600px']
                    };
                    Util.open(conf, function (action,data) {
                        if (action != 'ok') {
                            return;
                        }
                        if(callback) {
                            callback(this.$parent, data);
                        }
                    });
                })
            },
            addData(id, data) {
                var fields;
                if (id == "query") {
                    fields = this.returnFields;
                } else if (id == "where") {
                    fields = this.whereFields;
                } else if (id == "order") {
                    fields = this.orderFields;
                }
                var json = this.getJson(fields);
                for (var i = 0; i < data.length; i++) {
                    if (!json[data[i].fieldName]) {
                        //如果添加字段为排序字段且长度不小于三
                        if(id == "order" && fields.length >= 3){
                            this.$message.warning(this.i18n('isMsg.msg11',"排序字段个数不能超过三个！"));
                            break;
                        }
                        var row = data[i];
                        row.comment = row.fieldLabel;
                        //DataType//columnType
                        var datatype = row.dataType;
                        if (datatype == "string") {
                            datatype = "varchar";
                        }
                        row.columnType = datatype;
                        row.typeOperate = "=";
                        fields.push(row);
                    }
                }
                for (var i = 0; i < fields.length; i++) {
                    fields[i].idx_ = Util.randomId();
                }
                this.keys = 'k' + new Date().getTime();
            },
            getJson(data) {
                var obj = {};
                for (var j = 0; j < data.length; j++) {
                    obj[data[j].fieldName] = 1;
                }
                return obj;
            },
            moveUp(id) {
                var fields, selectedRowKeys;
                if (id == "query") {
                    fields = this.returnFields;
                    selectedRowKeys = this.selectedReturnRowKeys;
                } else if (id == "where") {
                    fields = this.whereFields;
                    selectedRowKeys = this.selectedWhereRowKeys;
                } else if (id == "order") {
                    fields = this.orderFields;
                    selectedRowKeys = this.selectedOrderRowKeys;
                }
                this.toUp(fields, selectedRowKeys);
            },
            moveDown(id) {
                var fields, selectedRowKeys;
                if (id == "query") {
                    fields = this.returnFields;
                    selectedRowKeys = this.selectedReturnRowKeys;
                } else if (id == "where") {
                    fields = this.whereFields;
                    selectedRowKeys = this.selectedWhereRowKeys;
                } else if (id == "order") {
                    fields = this.orderFields;
                    selectedRowKeys = this.selectedOrderRowKeys;
                }
                this.toDown(fields, selectedRowKeys);
            },
            removeFields(id) {
                var fields, selectedRowKeys;
                if (id == "query") {
                    fields = this.returnFields;
                    selectedRowKeys = this.selectedReturnRowKeys;
                } else if (id == "where") {
                    fields = this.whereFields;
                    selectedRowKeys = this.selectedWhereRowKeys;
                    for (var i = fields.length - 1; i >= 0; i--) {
                        var row = fields[i];
                        if (selectedRowKeys.includes(row.idx_)) {
                            this.sqlWhereField.splice(i + 1, 1);
                        }
                    }
                } else if (id == "order") {
                    fields = this.orderFields;
                    selectedRowKeys = this.selectedOrderRowKeys;
                }
                this.removeRows(fields, selectedRowKeys);
            },
            sqlRemoveFields(index){
                let obj=this.sqlWhereField[index];
                let fieldName=obj.value;
                for(let i=0;i<this.whereFields.length;i++){
                    let field=this.whereFields[i];
                    if(field.fieldName==fieldName){
                        this.whereFields.splice(i,1);
                    }
                }
                this.sqlWhereField.splice(index,1)
            },
            onSelectReturnChange(selectedRowKeys, selectedRows) {
                this.selectedReturnRowKeys = selectedRowKeys;
            },
            onSelectWhereChange(selectedRowKeys, selectedRows) {
                this.selectedWhereRowKeys = selectedRowKeys;
            },
            onSelectOrderChange(selectedRowKeys, selectedRows) {
                this.selectedOrderRowKeys = selectedRowKeys;
            },
            get(id) {
                return FormCustomQueryApi.get(id);
            },
            validForm(values) {
                //验证返回对象为空时提示
                if (!this.getReturnFields()) {
                    this.$message.error(this.i18n('form.msg4','返回字段必须设置！'))
                    return false;
                }
                return true;
            },
            save(values,vm) {
                if(!values.sqlBuildType){
                    values['sqlBuildType'] = this.mdl.sqlBuildType;
                }
                values.resultField = this.getReturnFields();
                values.whereField = this.getWhereFields();
                values.orderField = this.getOrderFields();


                if (values.sqlBuildType == "sql") {
                    values.sqlDiy = this.mdl.sqlDiy;
                }
                if(this.isTenant){
                    values.isTenant="1";
                    values.dsAlias="";
                }else {
                    values.isTenant="0";
                }
                return FormCustomQueryApi.save(values);
            },
            getReturnFields() {
                var fields = this.returnFields;
                if (fields.length == 0) {
                    return null;
                } else {
                    var arr = [];
                    for (var i = 0; i < fields.length; i++) {
                        var field = fields[i];
                        var json = {idx_: field["idx_"]};
                        json.comment = field.comment;
                        json.fieldName = field.fieldName;
                        json.reg = field.reg;
                        json.regName = field.regName;
                        arr.push(json);
                    }
                    return JSON.stringify(arr);
                }
            },
            getWhereFields() {
                var fields = this.whereFields;
                if (fields.length == 0) {
                    return JSON.stringify(fields);
                } else {
                    var arr = [];
                    var type = this.mdl.sqlBuildType;
                    for (var i = 0; i < fields.length; i++) {
                        var field = fields[i];
                        var json = {idx_: field["idx_"]};
                        json.comment = field.comment;
                        json.fieldName = field.fieldName;
                        json.columnType = field.columnType;
                        json.typeOperate = field.typeOperate;
                        json.valueSource = (type == "table") ? field.valueSource : "param";
                        json.valueDef = field.valueDef;
                        arr.push(json);
                    }
                    return JSON.stringify(arr);
                }
            },
            getOrderFields() {
                var fields = this.orderFields;
                if (fields.length == 0) {
                    return JSON.stringify(fields);
                } else {
                    var arr = [];
                    for (var i = 0; i < fields.length; i++) {
                        var field = fields[i];
                        var json = {idx_: field["idx_"]};
                        json.comment = field.comment;
                        json.fieldName = field.fieldName;
                        json.typeOrder = field.typeOrder;
                        arr.push(json);
                    }
                    return JSON.stringify(arr);
                }
            },
            sqlTypeChange(type,loadType) {
                //如果为初始化或者不存在条件不需要提示
                if (loadType=='init' || !(this.returnFields.length>0 || this.whereFields.length>0 || this.orderFields.length>0)){
                    this.switchingTypes(type)
                    return;
                }
                var self=this;
                this.$confirm({
                    content: "切换sql构建类型后会清空已配置的条件，是否确认切换？",
                    zIndex: 20004,
                    okText:"确定",
                    cancelText:"取消",
                    onOk() {
                        self.switchingTypes(type)
                    },
                });

            },
            //切换类型
            switchingTypes(type) {
                //table,sql,freeMarkerSql
                if(type){
                    this.mdl['sqlBuildType'] = type;
                    if (type == "table") {
                        this.isTable = true;
                        this.whereColumns = this.whereColumns;
                    } else {
                        this.isTable = false;
                        this.whereColumns.splice(4, 3);
                    }
                    if (type == "sql") {
                        this.isGroovy = true;
                    } else {
                        this.isGroovy = false;
                    }
                }
                //切换时清空数组
                this.returnFields = [];
                this.whereFields = [];
                this.orderFields = [];
            },
            sqlInsertChange(value) {
                this.$refs.sql.insertContent(value);
                this.sqlShow = "";
            },
            sqlDiyInsertChange(value) {
                this.$refs.sqlDiy.insertContent(value);
                this.sqlShow = "";
            },
            tabChange(activeKey) {
                if (activeKey == 'customSQL') {
                    this.sqlWhereField = [{label: this.i18n('form.optionalCondition','可选条件列头'), value: ''}];
                    this.sqlWhereField = this.sqlWhereField.concat(this.whereFields.map(where => {
                        return {label: where.comment, value: where.fieldName}
                    }));
                    this.setSqlDiy();
                }
            },
            setSqlDiy() {
                var sql = this.isGroovy?(this.mdl.sqlDiy?this.mdl.sqlDiy:this.mdl.sql):this.mdl.sql;
                //var sqlDiy = this.mdl.sqlDiy ;
                if (this.isGroovy  && sql.indexOf("return") == -1 ) {
                    sql = "String sql=\"" + sql + "\";\r\n return sql;";
                    this.mdl.sqlDiy=sql;
                } else {
                    this.mdl.sqlDiy=sql;
                }
                return sql;
            },
            openDataSource() {
                Dialog.openDataSourceDialog({
                    curVm: this, widthHeight: ['1200px', '600px'],
                    data: {}
                }, function (self, data) {
                    self.mdl.dsAlias= data.alias;
                })
            },
            openTableQuery() {
                let self_=this;
                Dialog.openTableQueryDialog({
                    curVm: this, widthHeight: ['1200px', '600px'], data: {ds: this.mdl.dsAlias}
                }, function (self, data) {
                    self_.mdl.tableName= data.tableName;
                    //切换时清空数组
                    self_.returnFields = [];
                    self_.whereFields = [];
                    self_.orderFields = [];
                })
            },
            openScriptQuery(record) {
                Dialog.openScripttextDialog({
                    curVm: this, widthHeight: ['1200px', '600px'], data: {script: record.valueDef}
                }, function (self, data) {
                    self.$set(record, 'valueDef', data)
                })
            },
            typeOrderChange(text, options) {
                this.orderFields[options.key].typeOrder = text;
            },
            typeOperateChange(text, options) {
                this.whereFields[options.key].typeOperate = text;
            },
            valueSourceChange(text, options) {
                this.whereFields[options.key].valueSource = text;
                this.$forceUpdate();
            },
            valueDefChange(text, index) {
                this.whereFields[index].valueDef = text;
            },
            valueDefTextChange(e,record,index) {
                record.valueDef = e.target.value;
                this.whereFields[index].valueDef = e.target.value;
            },
            customReturnRowFn(record) {
                this.customRowFn(record, this.selectedReturnRowKeys);
            },
            customWhereRowFn(record) {
                this.customRowFn(record, this.selectedWhereRowKeys);
            },
            customOrderRowFn(record) {
                this.customRowFn(record, this.selectedOrderRowKeys);
            },
            //删除已选择
            handleDeleteSelected(record, selectedRowKeys, index) {
                var idx = selectedRowKeys.indexOf(record['idx_'])
                selectedRowKeys.splice(idx, 1)
            },
            customRowFn(record, selectedRowKeys) {
                return {
                    on: {
                        click: () => {
                            let key = record['idx_']
                            let index = selectedRowKeys.indexOf(key)
                            if (index === -1) {
                                selectedRowKeys.push(key)
                            } else {
                                this.handleDeleteSelected(record, selectedRowKeys, index)
                            }
                        }
                    }
                }
            },
            insertExp(text) {
                if (!this.isTable) {
                    if (this.isGroovy) {
                        this.$refs.sqlDiy.insertContent(text);
                    } else {
                        this.$refs.sql.insertContent(text);
                    }
                }
            },
            insertTreeSql() {
                var treeSql = "SELECT *,(SELECT COUNT(*) FROM 表名 B WHERE B.父字段 = A.字段) CHILDS FROM 表名 A";
                this.insertExp(treeSql);
            },
            onSqlExp(e) {
                this.insertExp("$" + e.key)
                this.sqlShow = "";
            },
            //下一步
            nextStep(){
                this.$refs.form.validate(valid => {
                    if (valid) {
                        this.loadDataSource();
                    }
                });
            },
            //上一步
            backStep(){
                this.showok = false;
            }
        }
    }
</script>
<style scoped>
    .form-condition{
        cursor: pointer;
        color: #444444;
        font-size: 14px;
        display: flex;
    }
    .form-condition i {
        font-size: 18px;
        margin-top: 15px;
    }
    .opinion-parenthesis-add{
        border-top: solid 1px #d9d9d9;
        height: 35px;
        line-height: 35px;
        padding-left: 12px;
        cursor: pointer;
        color: #444444;
        display: flex;
        align-items: center;
    }
    .opinion-parenthesis-add i{
        font-size: 18px;
        margin-right: 5px;
    }
    .opinion-parenthesis-triangle{
        height: 5px;
        width: 0px;
        border: 10px solid;
        border-color: transparent transparent white transparent;
        position: absolute;
        top: -17px;
        left: 36px;
    }
    .opinion-parenthesis-list{
        margin-top: 20px;
    }
    .opinion-parenthesis-list li{
        color: #444444;
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 0px 12px;
        height: 30px;
        line-height: 30px;
        cursor: pointer;
    }
    .opinion-parenthesis-list li i{
        margin-right:5px;
        font-size: 18px;
    }
    .opinion-parenthesis-list li i:hover{
        color:#4285f4
    }
    .opinion-parenthesis-list li div{
        flex: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 1;
        -webkit-box-orient: vertical;
        padding-left: 5px;
    }
    .opinion-parenthesis-list li div:hover{
        background-color: #f2f3f6;
        border-radius: 4px;
    }
    .opinion-parenthesis{
        position: absolute;
        top: 42px;
        left:0px;
        width: 300px;
        background-color: #ffffff;
        box-shadow: 0px 0px 13px 0px
        rgba(6, 0, 1, 0.17);
        border: solid 1px #eeeeee;
        border-radius: 4px;
        z-index: 9;
    }
    .tableToolBar{
        padding-right: 0px;
    }
    .custom-layout >>> .ant-form{
        padding: 0px!important;
    }
    .conditionDiv-sql{
        display: flex;
        flex-direction: column;
        height: 100%;
        padding:10px 22px;
    }
    .conditionDiv-sql>div:nth-child(3){
        flex: 1;
        margin-bottom: 30px;
    }
    .div-containers-head{
        display: flex;
    }
    .div-containers-head >div:nth-child(2){
        flex: 1;
    }
    .div-containers-head-span{
        border-left: 2px solid #1890ff;
        font-size: 14px;
        height: 15px;
        display: block;
        line-height: 15px;
        padding-left: 5px;
        color: #46494d;
        margin-top: 10px;
    }
    .condition-field{
        display: flex;
        height: 100%;
    }
    .condition-field >div{
        flex: 1;
        border-right:1px solid #dadde0;
    }
    .div-containers-show{
        display: none;
    }
    .sqlBuildTypeList{
        display: flex;
    }
    .sqlBuildTypeList >div{
        width: 340px;
        min-height: 62px;
        border-radius: 4px;
        border: solid 1px #dadde0;
        margin-right: 20px;
        padding: 13px 11px;
        cursor: pointer;
        position: relative;
    }
    .sqlBuildTypeList >div:hover{
        border: solid 1px #4285f4;
    }
    .sqlBuildTypeList-show{
        border: solid 1px #4285f4!important;
    }
    .sqlBuildTypeList-child-iconfont{
        position: absolute;
        top: 0px;
        right: 0px;
        height:15px;
        width: 15px;
        border:15px solid;
        border-color:#4285f4  #4285f4 transparent  transparent ;
        text-align: center;
    }
    .sqlBuildTypeList-child-iconfont::before{
        content: '';
        position: absolute;
        display: inline-block;
        width: 5px;
        height: 8px;
        top: -11px;
        right: -9px;
        border-right: 2px solid #fff;
        border-bottom: 2px solid #fff;
        z-index: 9;
        transform: rotate(45deg);
    }
    .sqlBuildTypeList-child >div{
        height: 14px;
        line-height: 14px;
        color: #46494d;
        font-size: 14px;
    }
    .sqlBuildTypeList-child > span{
        display: block;
        line-height: 12px;
        font-size: 12px;
        color: #c0c5cc;
        margin-top: 10px;
    }
    .conditionDiv {
        display: flex;
        height: 50px;
    }
    .conditionDiv .minDiv {
        display: flex;
        align-items: center;
        position: relative;
        margin-right: 20px;
    }

    .conditionDiv .minDiv span {
        white-space: nowrap;
    }

    .ant-tabs .ant-tabs-content.ant-tabs-top-content {
        height: calc(100% - 50px);
    }

    .div-containers {
        padding: 10px;
        box-sizing: border-box;
    }
</style>